import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Link } from 'umi';
import { PlusOutlined, EllipsisOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Tag, Space, Modal, Popconfirm, message, } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import request from 'umi-request';
import { DataPoolItem } from './data';
import { getDataPool, deleteDataPool, editDataPool, addDataPool } from '../service';
import { history } from 'umi';
import DataSourceDialog, { DataSourceItem } from './components/DataSourceDialog';

const mocks = `
[
  {
      "name": "test",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "数据池2",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "shuju",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool4",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool5",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool6",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool7",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool8",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool9",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool10",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  },
  {
      "name": "pool11",
      "description": "这是一个测试用数据池",
      "creator": "",
      "sourceNum": 5,
      "createdAt": 122,
      "updateAt": 120
  }
]
`;

const DataPoolList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [curData, setCurData] = useState<DataSourceItem | null>(null);
  const dsDialogRef = useRef(null);

  const onClickETL = (record: DataPoolItem) => {
    // history.push(`/etl/${record.id}`);
  }

  const onClickEdit = (record: DataPoolItem) => {
    const { id, name, description } = record;
    setCurData({ id, name, description });
    setIsModalVisible(true);
  }

  const onClickDatasouce = (record: DataPoolItem) => {
    // history.push(`/datasource/${record.id}`);
  }

  const delDataPool = async (record: DataPoolItem) => {
    // const { code, data, msg } = await deleteDataPool(record.id);
    // if (code === 0) {
    //   message.success('删除成功');
    // } else {
    //   message.error(`删除失败：${msg}`);
    // }
  }



  const columns: ProColumns<DataPoolItem>[] = [
    {
      title: '数据池名称',
      dataIndex: 'name',
      align: 'center',
      // copyable: true,
      ellipsis: true,
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '此项为必填项',
      //     },
      //   ],
      // },
    },
    {
      title: '描述',
      align: 'center',
      dataIndex: 'description',
      valueType: 'text',
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creator',
      valueType: 'text',
      search: false,
      // renderFormItem: (_, { defaultRender }) => {
      //   return defaultRender(_);
      // },
      // render: (_, record) => (
      //   <Space>
      //     {record.labels.map(({ name, color }) => (
      //       <Tag color={color} key={name}>
      //         {name}
      //       </Tag>
      //     ))}
      //   </Space>
      // ),
    },
    {
      title: '数据源个数',
      align: 'center',
      key: 'sourceNum',
      dataIndex: 'sourceNum',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      align: 'center',
      key: 'createdAt',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '修改时间',
      align: 'center',
      key: 'updateAt',
      dataIndex: 'updateAt',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Space size='small'>
          <Button type='link' size='small' onClick={() => onClickETL(record)}>数据ETL</Button>
          <Button type='link' size='small' onClick={() => onClickEdit(record)}>编辑</Button>
          <Button type='link' size='small' onClick={() => onClickDatasouce(record)}>数据源</Button>
          <Popconfirm
            title="删除后将无法恢复，是否继续？"
            onConfirm={() => delDataPool(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='link' size='small' danger >删除</Button>
          </Popconfirm>
        </Space>
      ],
    },
  ];

  const onClickAdd = () => {
    setCurData(null);
    setIsModalVisible(true);
  }

  const onHandleOk = async () => {
    const res = await dsDialogRef?.current?.form.validateFields();

    // 字段验证未通过
    if (Object.keys(res).includes('errorFields')) {
      return;
    }

    // 编辑
    if (curData?.id) {
      const { code, data, msg } = await editDataPool(curData?.id, res);

      if (code === 0) {
        message.success('编辑成功！');
      }
    } else {  //新增
      const { code, data, msg } = await addDataPool(res);

      if (code === 0) {
        message.success('新增成功！');
      }
    }
  }

  const onHandleCancel = () => {
    setIsModalVisible(false);
  }

  return (
    <PageContainer>
      <ProTable<DataPoolItem>
        columns={columns}
        actionRef={actionRef}
        // request={async (params = {}, sort, filter) => {
        //   console.log(params, sort, filter);
        //   return Promise.resolve(params);

        //   // // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        //   // // 如果需要转化参数可以在这里进行修改
        //   // const queries = constructQueries(params, sort, filter);

        //   // const res = await getDataPool();

        //   // return {
        //   //   data: res.data.items,
        //   //   // success 请返回 true，
        //   //   // 不然 table 会停止解析数据，即使有数据
        //   //   success: true,
        //   //   // 不传会使用 data 的长度，如果是分页一定要传
        //   //   total: res.data.total,
        //   // };
        // }}        
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        // form={{
        //   // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        //   syncToUrl: (values, type) => {
        //     if (type === 'get') {
        //       return {
        //         ...values,
        //         createdAt: [values.startTime, values.endTime],
        //       };
        //     }
        //     return values;
        //   },
        // }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onClickAdd}>
            新建
          </Button>
        ]}
        options={{ reload: true, setting: false, density: false }}
        defaultData={JSON.parse(mocks)}
      />
      {
        isModalVisible && (
          <DataSourceDialog ref={dsDialogRef} data={curData} handleOk={onHandleOk} handleCancel={onHandleCancel} />
        )
      }
    </PageContainer>
  )
}

export default DataPoolList;